import axios from 'axios'
import router from '@/router'
import store from '@/store'
import Vue from 'vue'
import { getToken, removeToken } from '@/utils/auth'
import md5 from 'js-md5'
import des from '@/utils/des'
// import { parseTime } from '@/utils';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000
})
// request interceptor
service.interceptors.request.use(
  config => {
    // header插入token
    config.headers['X-JSZS-TOKEN'] = getToken() || store.getters.user.token
    // 加密
    let value = ''
    let params = ''
    const s = config.url
    // 接口为登录时候传入验证码randstr
    if (s.indexOf('/auth/login') > -1) {
      config.headers['randstr'] = store.getters.randstr
    }
    // 如果是分页接口或者需要存入参数的接口则存入查询参数作为导出的筛选条件
    // const needKeepParamArr = ['/data/statistics/page'];
    if (config.data && config.data.pageSize && config.data.pageNum) {
      // 剔除所有入参为null的参数
      for (const key in config.data) {
        if (config.data[key] === null || config.data[key] === '') {
          delete config.data[key]
        }
      }

      const pagination = {
        pageSize: config.data.pageSize,
        pageNum: config.data.pageNum
      }
      store.commit('SET_PAGINATION', pagination)
    }
    if (process.env.VUE_APP_DES === 'true') {
      if (config.method.toLocaleUpperCase() === 'GET') {
        value = config.url.replace(/\/|\.|:|&|\?|=/g, '')
        const key = process.env.VUE_APP_KEY
        for (const key in config.params) {
          const ketItem = key + config.params[key]
          params += ketItem
        }
        const concatValue = config.url.includes('?') ? '&' : '?'

        config.url = config.url + `${concatValue}sign=${md5(key + value + params).toLocaleUpperCase()}`
      } else {
        const timestamp = new Date().getTime()
        const key = 'list' + timestamp
        const keyV = {}
        let configUrl = config.url
        if (config.url.indexOf('//') > -1) {
          configUrl = configUrl.replace('//', '/')
        }
        keyV[key] = configUrl
        console.log(configUrl)
        const data = Object.assign(keyV, config.data)
        config.data = { body: des.jiami(data) }
      }
    }
    return config
  },

  error => {
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.status === 200 && response.config.responseType === 'blob') {
      if (response.data.size === 0 || response.headers['content-type'].includes('json')) {
        const data = response.data
        const fileReader = new FileReader()
        fileReader.readAsText(data)
        fileReader.onload = function(result) {
          const jsondata = JSON.parse(result.target.result)
          Vue.prototype._message.error({
            message: `${jsondata.msg}`,
            duration: 3 * 1000
          })
        }
        return Promise.reject(response)
      }
      return response
    } else {
      const res = response.data
      if (res.code === 0) {
        return Promise.resolve(res)
      } else if (res.code === 'ERROR_AUTH_LOGIN') {
        Vue.prototype._message.error({
          message: `${res.msg}`,
          duration: 3 * 1000
        })
        removeToken()
        router.replace({
          name: 'Login',
          query: { url: window.location.href }
        })
      } else if (res.code === 'STOP_DATA') {
        removeToken()
        Vue.prototype._message.error({
          message: res.msg,
          duration: 3 * 1000
        })
        router.replace({
          name: 'Login'
        })
      } else if (res.code === 'ERROR_AUTH_OPERATE') {
        router.push({ name: 'Error500', query: { msg: encodeURIComponent(res.msg) }})
      } else if (res.msg) {
        Vue.prototype._message.error({
          message: res.msg,
          duration: 3 * 1000
        })
        // 非5xx的错误属于业务错误，留给具体页面处理
        return Promise.reject(res)
      } else {
        return response
      }
    }
  },
  error => {
    Vue.prototype._message.error({
      message: '服务器拒绝访问，请联系系统管理员',
      duration: 3 * 1000
    })
    // router.replace({ name: 'Error500' });
    return Promise.reject(error)
  }
)
export default service
